package com.piggy.settlement.sdk.util;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ：daxia
 * @description：XML工具类
 * @modified By：
 * @version: 1.0$
 */
public class PiggyXmlUtil {

    private static ConcurrentHashMap<Class, JAXBContext> jaxbContMap = new ConcurrentHashMap<Class, JAXBContext>();

    public static String objectToXml(Object obj) throws JAXBException {
        StringWriter sw = new StringWriter();
        JAXBContext context = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        sw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
        marshaller.marshal(obj, sw);
        return sw.toString();
    }

    public static <T> T xmlToObject(String xmlStr, Class<T> c) throws Exception {
        JAXBContext context = jaxbContMap.get(c);
        if (context == null) {
            synchronized (c) {
                context = JAXBContext.newInstance(c);
                jaxbContMap.put(c, context);
            }
        }
        Unmarshaller unmarshaller = context.createUnmarshaller();
        T t = (T) unmarshaller.unmarshal(new StringReader(xmlStr));
        return t;
    }

}
